<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Product extends Model
{
    protected $guarded = ['id'];
    
    protected $appends = ['point','month_sale','con_price','discount','sale_num','end_time'];                        
    protected $casts = ['price'];    
    


    public function cate()
    {
    	return $this->belongsTo(Cate::class,'cate_id');
    }

    

   

    public function imgs()
    {
        return $this->hasMany(ProductImg::class);
    }

    public function getPointAttribute()
    {
        return 5;
    }

    public function getDiscountAttribute()
    {
        $num = 0;
        if($this->market_price) {
          $num = $this->price/$this->market_price;  
        }
        
        return round($num,1)*10;
    }

  

    public function getMonthSaleAttribute()
    {
        $month = date('m');
        $num =  OrderProduct::where('product_id',$this->id)
                            ->whereMonth('created_at',$month)
                            ->sum('product_num');
        return (int)$num;                    
    }

     public function getSaleNumAttribute()
    {
        
        $num =  OrderProduct::where('product_id',$this->id)                                        
                            ->sum('product_num');
        return (int)$num;                    
    }

   

    public function getConPriceAttribute()
    {
        return $this->price/100;
    }

    public function getSaleTxtAttribute()
    {
        return $this->status==1?'销售中':'已下架';
    }

     public function getEndTimeAttribute()
    {
        return strtotime($this->end_at);
    }

    public function  productSpec()
    {
        return $this->hasMany(ProductSpec::class);
    }


    
}
